import React, { useEffect, useRef, useState } from 'react'
import style from './Components/OrderList.less'
import { Button, DatePicker, DatePickerRef, Dropdown, ErrorBlock, Form, Input, Picker, SearchBar, Selector, Space } from 'antd-mobile'
import { useTitle } from 'ahooks'
import { DropdownRef } from 'antd-mobile/es/components/dropdown'
import { FormItem } from 'antd-mobile/es/components/form/form-item';
import datas from '../Invoice/Components/data.svg'
import dkp from '../Invoice/Components/dkp.svg'
import kpz from '../Invoice/Components/kpz.svg'
import yqx from '../Invoice/Components/yqx.svg'
import dayjs from 'dayjs'
import moment from 'moment'
import { DelBill, QueryBillList, cancelBill, queryBillById } from '@/services/Title';


export default function OrderSList() {
  const [filter, setFilter] = useState<number>(1);
  const [filterValues, setFilterValues] = useState<API.QueryBillListInfo | null>()
  const [Lists, setLists] = useState([])
  const dropdownRef = useRef<DropdownRef>(null)
  const [form] = Form.useForm()
  useTitle("订单列表")
  const Search = (data: any) => {
    console.log(data);
    const temp = {
      endTime: filterValues?.endTime ?? undefined,
      enterprise: String(data),
      goodsName: String(data),
      startTime: filterValues?.startTime ?? undefined,
    }
    setFilterValues(temp)
  }
  const onButtons = (data: any) => {
    setFilter(data)
  }
  const onInvoicing = async (data: any) => {
    // console.log(data);
    const res = await queryBillById(data)
    console.log(res);

    // const value = {...item,}
    //       history.push(
    //         '/Invoice/RefineOrder',
    //      )
  }
  const onFinish = (data: any) => {
    console.log('onFinish', data, moment(data?.startTime).format('YYYY-MM-DD HH:mm:ss'));
    setFilterValues(data)
    setFilter(data.status)
  }
  const handleCancel = async (data: any) => {
    console.log(data);
    const res = await cancelBill(data);
    getDate()

  }
  const handleDel = async (data: any) => {
    console.log(data);
    const res = await DelBill(data);
    getDate()

  }

  const options = [
    {
      label: <span style={{ fontSize: "15px" }}>近一个月</span>,
      value: 1,
    },
    {
      label: <span style={{ fontSize: "15px" }}>近三个月</span>,
      value: 3,
    },
    {
      label: <span style={{ fontSize: "15px" }}>近六个月</span>,
      value: 6,
    },
  ]
  const basicColumns = [[
    { label: '全部', value: 1 },
    { label: '已开票', value: 4 },
    { label: '开票中', value: 3 },
    { label: '待开票', value: 2 },
    { label: '已取消', value: 5 },
  ],]
  const getDate = async () => {
    const value = {
      status: filter == 1 || filter == null ? '' : filter == 2 ? '待开票' : filter == 3 ? '开票中' : filter == 4 ? "已开票" : '已取消',
      // createTime: filterValues.,
      endTime: filterValues?.endTime,
      enterprise: filterValues?.enterprise,
      goodsName: filterValues?.goodsName,
      startTime: filterValues?.startTime,
    }
    // console.log(value);

    const res = await QueryBillList(value)
    if (res.length) {
      setLists(res)
    }

    // console.log(res);

  }
  useEffect(() => {
    getDate()
  }, [filter, filterValues])
  return (
    <>
      <div style={{ height: "50px" }}>
        <SearchBar
          onSearch={Search}
          placeholder='搜索订单'
          // showCancelButton
          style={{
            '--border-radius': '100px',
            '--background': 'rgba(245, 245, 245, 1)',
            '--height': '34px',
            padding: "10px"
          }} />
      </div>
      <div style={{ height: "45px", padding: "10px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: 'flex', justifyContent: "space-evenly", flex: "1", maxWidth: "90%" }}>
          <Button shape='rounded' onClick={() => onButtons(1)} style={{ width: "50px", height: "25px", background: filter == 1 ? "rgba(33, 180, 124, 0.07)" : "#F3F3F3", display: 'flex', justifyContent: "center", alignItems: "center", border: filter == 1 ? "1px solid #21B47C" : "", marginRight: "7px" }}><span style={{ fontSize: "14px", whiteSpace: "nowrap" }}>全部</span></Button>
          <Button shape='rounded' onClick={() => onButtons(2)} style={{ width: "60px", height: "25px", background: filter == 2 ? "rgba(33, 180, 124, 0.07)" : "#F3F3F3", display: 'flex', justifyContent: "center", alignItems: "center", border: filter == 2 ? "1px solid #21B47C" : "", marginRight: "7px" }}><span style={{ fontSize: "14px", whiteSpace: "nowrap" }}>待开票</span></Button>
          <Button shape='rounded' onClick={() => onButtons(3)} style={{ width: "60px", height: "25px", background: filter == 3 ? "rgba(33, 180, 124, 0.07)" : "#F3F3F3", display: 'flex', justifyContent: "center", alignItems: "center", border: filter == 3 ? "1px solid #21B47C" : "", marginRight: "7px" }}><span style={{ fontSize: "14px", whiteSpace: "nowrap" }}>开票中</span></Button>
          <Button shape='rounded' onClick={() => onButtons(4)} style={{ width: "60px", height: "25px", background: filter == 4 ? "rgba(33, 180, 124, 0.07)" : "#F3F3F3", display: 'flex', justifyContent: "center", alignItems: "center", border: filter == 4 ? "1px solid #21B47C" : "" }}><span style={{ fontSize: "14px", whiteSpace: "nowrap" }}>已开票</span></Button>
        </div>
        <div >
          <Dropdown ref={dropdownRef}>
            <Dropdown.Item key='sorter' title={<span style={{ fontSize: "15px" }}>筛选</span>}>
              <div className={style.filter}>
                <Form
                  form={form}
                  onFinish={onFinish}
                  footer={
                    <div className={style.footer}>
                      <Button onClick={() => {
                        form.resetFields()
                        setFilterValues(null)
                        setFilter(1)
                        // dropdownRef.current?.close()
                      }} style={{ width: "39%", "--text-color": "#21B47C", border: "1px solid #21B47C" }}>重置</Button>
                      <Button onClick={() => { onFinish(form.getFieldsValue()), dropdownRef.current?.close() }} style={{ width: "59%", "--text-color": "#FFFFFF", background: "#21B47C", }}>确认</Button>
                    </div>
                  }
                >
                  {/* <div>下单时间</div> */}
                  <div className={style.div2}>
                    <Form.Item
                      label='下单时间'
                      name='selector'
                      help="月份筛选与时间段筛选冲突">
                      <Selector
                        options={options}
                        showCheckMark={false}
                        columns={3}
                        onChange={(arr, extend) => {
                          form.resetFields(['endTime', 'startTime'])
                          console.log(arr, extend.items)
                        }}
                        style={{
                          '--border': 'solid transparent 1px',
                          "--gap": "14px",
                          "--checked-text-color": "#21B47C",
                          '--checked-border': 'solid #21B47C 1px',
                          "--checked-color": "rgba(239,250,246)",
                        }} />
                    </Form.Item>
                    <div style={{ display: "flex", justifyContent: "space-evenly", alignItems: "center" }}>
                      <div className={style.startTime}>
                        <Form.Item
                          name='startTime'
                          trigger='onConfirm'
                          // style={{height:"35px"}}
                          onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                            form.resetFields(['selector'])
                            datePickerRef.current?.open()
                          }}>
                          <DatePicker precision='minute' >
                            {value =>
                              value ? <span style={{ whiteSpace: "nowrap" }}>{dayjs(value).format('YYYY-MM-DD')}</span> : <span style={{ 'fontSize': '15px', color: 'rgba(153, 153, 153, 1)', whiteSpace: "nowrap" }}>开始时间</span>
                            }
                          </DatePicker>
                        </Form.Item>
                      </div>
                      <div>—</div>
                      <div className={style.endTime}>
                        <Form.Item
                          name='endTime'
                          // rules={[{
                          //   required:  true,
                          //   message: '请填写完整',
                          // }]}
                          trigger='onConfirm'
                          onClick={(e, datePickerRef: RefObject<DatePickerRef>) => {
                            form.resetFields(['selector'])
                            datePickerRef.current?.open()
                          }}>
                          <DatePicker precision='minute' >
                            {value =>
                              value ? <span style={{ whiteSpace: "nowrap" }}>{dayjs(value).format('YYYY-MM-DD')}</span> : <span style={{ 'fontSize': '15px', color: 'rgba(153, 153, 153, 1)', whiteSpace: "nowrap" }}>结束时间</span>
                            }
                          </DatePicker>
                        </Form.Item>
                      </div>
                    </div>
                  </div>
                  <div className={style.input_1}>
                    <Form.Item
                      label={<span className={style.form_span}>付款方名称</span>}
                      name='enterprise'
                    >
                      <Input placeholder='请输入' style={{ width: "94%", "--font-size": "15px", border: "1px solid #EAEAEC", borderRadius: "4px", height: "35px", paddingLeft: "18.75px" }} />
                    </Form.Item>
                  </div>
                  <div className={style.input_1}>
                    <Form.Item
                      label={<span className={style.form_span}>货物分类名称名称</span>}
                      name='goodsName'>
                      <Input placeholder='请输入' style={{ "--font-size": "15px", width: "94%", border: "1px solid #EAEAEC", borderRadius: "4px", height: "35px", paddingLeft: "18.75px" }} />
                    </Form.Item>
                  </div>
                  <div className={style.input_1}>
                    <Form.Item
                      label={<span className={style.form_span}>状态</span>}
                      name='status'>
                      <Picker
                        columns={basicColumns}
                        // value={value}
                        // onConfirm={setValue}
                        onSelect={(val, extend) => {
                          console.log('onSelect', val, extend.items)
                          form.setFieldValue('status', val)
                        }}
                      >
                        {(items, { open }) => {
                          return (
                            <Space align='center' style={{ display: 'block' }}>
                              <Input style={{ width: "94%", border: "1px solid #EAEAEC", borderRadius: "4px", height: "35px", paddingLeft: "18.75px" }}
                                onClick={open} value={items.every(item => item === null)
                                  ? '未选择'
                                  : items.map(item => item?.label ?? '未选择').join(' - ')} />

                            </Space>
                          )
                        }}
                      </Picker>
                    </Form.Item>
                  </div>

                </Form>
              </div>
            </Dropdown.Item>
          </Dropdown>
        </div>
      </div>
      {Lists.length != 0 ?
        <div className={style.styles}>
          {Lists?.map((item, index) => {
            return (
              <div className={style.lists} key={index}>
                <div className={style.lists_1}>
                  <div style={{ fontSize: "13px" }}>{moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')}</div>
                  {item.status == '待开票' ? <img style={{ width: "54.5px" }} src={dkp} alt="" /> :
                    item.status == '已取消' ? <img src={yqx} style={{ width: "54.5px" }} /> :
                      item.status == '开票中' ? <img src={kpz} style={{ width: "54.5px" }} /> :
                        <div className={style.listStatus}>已开票</div>}
                </div>
                <div className={style.lists_2}>{item.enterprise}</div>
                <div className={style.list_3}>
                  <div className={style.list3_1}>
                    <div className={style.list3_inner}>
                      <div style={{ marginRight: "5px" }}>货劳明细</div>
                      <div style={{ maxWidth: "140px", flex: 1, textOverflow: "ellipsis", overflow: "hidden" }}>{item.goodsName}</div>
                    </div>
                    <span style={{ color: "#BC944E", whiteSpace: "nowrap" }}>接口拿状态</span>
                  </div>
                  <div className={style.list3_inner}>
                    <div style={{ marginRight: "5px" }}>开票金额</div>
                    <div className={style.lists_2}>¥&nbsp;{item.receiptAll}</div>
                  </div>
                </div>
                <div className={style.list_4}>
                  {item.status == '已取消' ?
                    <div onClick={() => handleDel(item.billOrderPhone)} style={{ fontSize: "13px", whiteSpace: "nowrap" }}>删除订单</div> :
                    <div onClick={() => handleCancel(item.billOrderPhone)} style={{ fontSize: "13px", whiteSpace: "nowrap" }}>取消订单</div>}
                  <Button onClick={() => { onInvoicing(item.billOrderPhone) }} style={{ margin: "0 0 0 10px", whiteSpace: "nowrap", fontSize: "13px", border: "1px solid #CCCCCC", "--border-radius": "4px" }}>订单详情</Button>
                  {item.invoicingMethod == '先开发票' ? <Button onClick={() => { onInvoicing(item.billOrderPhone) }} style={{ whiteSpace: "nowrap", margin: "0 0 0 10px", fontSize: "13px", border: "1px solid #21B47C", "--text-color": "#21B47C" }}>上传凭证</Button> : ''}
                  {item.status == "待开票" ? <Button style={{ fontSize: "13px", margin: "0 0 0 10px", border: "1px solid #21B47C", whiteSpace: "nowrap", "--text-color": "#21B47C" }}>开票</Button> : ''}
                </div>
              </div>

            )
          })}
          {/* <div style={{height:"100px",background:"red"}}> </div> */}
        </div> :
        <ErrorBlock status='empty' />}
    </>
  )
}
